package com.example.weathermvvm.data

import android.util.Log
import com.example.weathermvvm.data.db.WeatherDao
import com.example.weathermvvm.data.model.weather.Weather
import com.example.weathermvvm.data.network.api.WeatherNetwork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 *
 * @Author： LJH
 * @Time： 2022/8/15
 * @description：天气数据仓库
 */
class WeatherRepository private constructor(private val weatherDao:WeatherDao,private val network: WeatherNetwork){

    /**
     * 从WeatherRepository 仓库里获取数据
     * 先从缓存里获取数据，缓存里没有数据则从网络获取
     * @param weatherId String
     * @return Weather
     */
    suspend fun getWeather(weatherId:String):Weather{
        Log.e("WeatherRepository","getWeather")
        var weather = weatherDao.getCachedWeatherInfo()
        if (weather == null){
            weather = requestWeather(weatherId)
        }
        return weather
    }

    /**
     * 刷新天气数据
     * @param weatherId String
     * @return Weather
     */
    suspend fun refreshWeather(weatherId: String) = requestWeather(weatherId)

    /**
     * 判断是否缓存有天气数据
     * @return Boolean
     */
    fun isWeatherCached() = weatherDao.getCachedWeatherInfo() != null

    /**
     * 获取缓存的天气数据
     * @return Weather
     */
    fun getWeatheredInfo() = weatherDao.getCachedWeatherInfo()!!

    /**
     * 从网络中获取天气数据
     * @param weatherId String
     * @return Weather
     */
    private suspend fun requestWeather(weatherId:String) = withContext(Dispatchers.IO){
        val heWeather = network.fetchWeather(weatherId)
        val weather = heWeather.weather!![0]
        weatherDao.cacheWeatherInfo(weather)
        weather
    }

    /**
     * 从网络中获取图片路径，并存到缓存中
     * @return String
     */
    private suspend fun requestBingPic() = withContext(Dispatchers.IO){
        val url = network.fetchBingPic()
        weatherDao.cacheBingPic(url)
        url
    }

    suspend fun getBingPic():String{
        var url = weatherDao.getCachedBingPic()
        if (url == null) url = network.fetchBingPic()
        return url
    }

    /**
     * 刷新图片
     * @return String
     */
    suspend fun refreshBingPic() = requestBingPic()

    companion object{
        private lateinit var instance:WeatherRepository
        fun getInstance(weatherDao: WeatherDao,network: WeatherNetwork):WeatherRepository{
            if (!::instance.isInitialized){
                synchronized(WeatherRepository::class.java){
                    if (!::instance.isInitialized){
                        instance = WeatherRepository(weatherDao,network)
                    }
                }
            }
            return instance
        }
    }
}